package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author tzp
 * @since 2020/9/14
 */
public class LC993 implements TreeProblem {
    public boolean isCousins(TreeNode root, int x, int y) {
        if (root == null) return false;

        Deque<TreeNode> xx = new ArrayDeque<>();
        xx.add(root);
        TreeNode sep = root;
        int level = 0, x_level = -1, y_level = -1, x_parent = -1, y_parent = -1;
        while (xx.size() != 0) {
            TreeNode node = xx.pollFirst();

            if (node.right != null) {
                xx.addLast(node.right);
                if (node.right.val == x) {
                    x_level = level;
                    x_parent = node.val;
                }
                if (node.right.val == y) {
                    y_level = level;
                    y_parent = node.val;
                }
            }
            if (node.left != null) {
                xx.addLast(node.left);
                if (node.left.val == x) {
                    x_level = level;
                    x_parent = node.val;
                }
                if (node.left.val == y) {
                    y_level = level;
                    y_parent = node.val;
                }
            }
            if (node == sep) {
                level++;
                if (xx.size() > 0) {
                    sep = xx.getLast();
                }
            }
        }

        if (x_level != -1 && x_level == y_level && x_parent != y_parent) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC993().isCousins(treeNode, 13, 11));
    }
}
